package com.qf.fmall.orders.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.fmall.index.entity.Product;
import com.qf.fmall.index.mapper.ProductMapper;
import com.qf.fmall.orders.entity.OrderItem;
import com.qf.fmall.orders.entity.Orders;
import com.qf.fmall.orders.mapper.OrderItemMapper;
import com.qf.fmall.orders.mapper.OrdersMapper;
import com.qf.fmall.orders.service.IOrdersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.fmall.product.entity.ProductSku;
import com.qf.fmall.product.mapper.ProductSkuMapper;
import com.qf.fmall.shopcart.entity.ShoppingCart;
import com.qf.fmall.shopcart.mapper.ShoppingCartMapper;
import com.qf.fmall.shopcart.service.IShoppingCartService;
import com.qf.fmall.utils.WXpayUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 订单  服务实现类
 * </p>
 *
 * @author weijy
 * @since 2024-01-18
 */
@Slf4j
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {

    @Autowired
    private IShoppingCartService shoppingCartService;

    @Autowired
    private ProductSkuMapper productSkuMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Override
    public HashMap<String, Object> addOrders(List<String> cids, Orders orders) throws ParseException {


        //1. 考虑购买商品的库存是否足够，够的话扣减库存，如果不够，抛出异常
        List<ShoppingCart> cartList = shoppingCartService.getListByCids(cids);

        List<Integer> productIds = new ArrayList<>();
        for (ShoppingCart cart : cartList) {
            productIds.add(cart.getProductId());
        }

        List<ProductSku> skuList = productSkuMapper.selectList(new QueryWrapper<ProductSku>().in("product_id", productIds));

        for (ShoppingCart cart : cartList) {

            // 购买量
            String cartNum = cart.getCartNum();
            // 库存量
            String stock = cart.getStock();

            if (Integer.valueOf(cartNum) <= Integer.valueOf(stock)) {
                String skuId = cart.getSkuId();
                ProductSku productSku = new ProductSku();
                productSku.setSkuId(Integer.valueOf(skuId));
                productSku.setStock(Integer.valueOf(cartNum));
                productSkuMapper.updateById(productSku);
            } else {
                log.info("库存不足");
                throw new RuntimeException("商品库存不足,下单失败");
            }
        }

        //2. 向 orders表写入数据
        //2.1 生成订单ID
        String orderID = UUID.randomUUID().toString().replaceAll("-", "");
        orders.setOrderId(orderID);

        // 处理订单中的商品名称
        StringBuffer stringBuffer = new StringBuffer();
        for (ProductSku productSku : skuList) {
            String skuName = productSku.getSkuName();
            stringBuffer.append(skuName)
                    .append(",");
        }
        String skuNames = stringBuffer.toString();
        orders.setUntitled(skuNames);

        orders.setStatus("0"); // 订单待支付

        orders.setDeleteStatus(0); // 订单状态为未删除
        Date date = new Date();
        orders.setCreateTime(date);
        orders.setUpdateTime(date);

        save(orders); // 保存订单数据

        //3. 向 order_item 写入数据
        for (ShoppingCart cart : cartList) {
            OrderItem orderItem = new OrderItem();

            //1. 生成主键
            String itemId = UUID.randomUUID().toString().replaceAll("-", "");
            orderItem.setItemId(itemId);
            orderItem.setOrderId(orderID);
            orderItem.setProductId(cart.getProductId() + "");
            orderItem.setProductName(cart.getProductName());
            orderItem.setProductImg(cart.getProductImg());
            orderItem.setSkuId(cart.getSkuId());
            orderItem.setSkuName(cart.getSkuName());
            orderItem.setProductPrice(cart.getProductPrice());
            orderItem.setBuyCounts(Integer.valueOf(cart.getCartNum()));
            BigDecimal totalAmount = new BigDecimal(cart.getCartNum()).multiply(cart.getProductPrice());
            orderItem.setTotalAmount(totalAmount);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date basketDate = simpleDateFormat.parse(cart.getCartTime());
            orderItem.setBasketDate(basketDate);
            orderItem.setIsComment(0);
            orderItemMapper.insert(orderItem);
        }


        //4. 删除购物车中的对应的数据
        shoppingCartService.removeBatchByIds(cids);

        //5. 调用微信支付获取 支付url
        String payUrl = WXpayUtils.getPayUrl(skuNames, orderID, orders.getActualAmount());

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("orderId", orderID);
        hashMap.put("productNames", skuNames);
        hashMap.put("payUrl", payUrl);

        return hashMap;
    }

    @Override
    public boolean getStatus(String orderId) {

        return WXpayUtils.getSatus(orderId);
    }


}
